<?php #//v.3.3.0
#///////////////////////////////////////////////////////
#// COPYRIGHT 2007 Phpauction.net ALL RIGHTS RESERVED //
#///////////////////////////////////////////////////////

include "../includes/config.inc.php";
include "loggedin.inc.php";
include $include_path."countries.inc.php";

function num_space($num){
  $ret ="";
  for($i=0;$i<$num;$i++)
    $ret .= "&nbsp;";
  return $ret;
}

$username = $name;
//-- Data check
if(!$_REQUEST[id]) {
	$URL = $_SESSION["RETURN_LIST"]."?offset=".$_SESSION['RETURN_LIST_OFFSET'];
    unset($_SESSION["RETURN_LIST"]);
    header("Location: $URL");
    exit;
}

/*
*        If script is called to actually make modifications
*        (ie on first invocation this script just displays some HTML
*         on the second it tries to modify the database).
*/

if($_POST['action'] && phpa_securepost($_POST)) {
    
    $query="";
    if(isset($_POST["ntxt"])) {
        foreach($_POST["ntxt"] as $k=>$v) {
            if(empty($v) && isset($txt[$k]) && !empty($txt[$k])) {
                $query.=",txt$k=\"".urldecode($txt[$k])."\"";
            } else $query.=",txt$k=\"$v\"";
            
        }
    }
    if(isset($_POST["nnum"])) {
        foreach($_POST["nnum"] as $k=>$v) {
            if(empty($v) && isset($num[$k]) && !empty($num[$k])) {
                $query.=",num$k=\"".$num[$k]."\"";
            } else $query.=",num$k=\"$v\"";
        }
    }
	
    // Check that all the fields are not NULL
    if ($_POST["id"] && $_POST["title"] && $_POST["category"] &&
    $_POST["description"]) {

        $DATE = explode("/",$_POST["date"]);
        if($SETTINGS[datesformat] == "USA") {
          $tmp_day          = $DATE[1];
          $tmp_month        = $DATE[0];
          $tmp_year         = $DATE[2];
        } else {
          $tmp_day          = $DATE[0];
          $tmp_month        = $DATE[1];
          $tmp_year         = $DATE[2];
        }

        /*
        *         Check the input values for validity.
        */
        if(strlen($tmp_year) == 2) {
            $tmp_year = "19".$tmp_year;
        }
        
        if (!ereg("^[0-9]{2}/[0-9]{2}/[0-9]{4}$",$_POST["date"]) &&
        !ereg("^[0-9]{2}/[0-9]{2}/[0-9]{2}$",$_POST["date"])) { //date check
          $ERR = "ERR_700";
        } else if ($_POST["quantity"] < 1) { // 1 or more items being sold
          $ERR = "ERR_701";
        } else if ($_POST["current_bid"] < $_POST["min_bid"] && $_POST["current_bid"] != 0) {    // bid > min_bid
          $ERR = "ERR_702";
        } else {
            #// Retrieve auction's data
            $query = "SELECT * from PHPAUCTIONXL_auctions where id='".$_POST["id"]."'";
            $res = @mysql_query($query);
            if(!$res) {
                MySQLError($query);
                exit;
            } elseif(mysql_num_rows($res) == 0) {
                print $ERR_606;
                exit;
            } else {
                $AUCTION = mysql_fetch_array($res);
                $T = mktime(substr($AUCTION['starts'], 8, 2),
                    substr($AUCTION['starts'], 10, 2),
                    substr($AUCTION['starts'], 12, 2),
                    $tmp_month,
                    $tmp_day,
                    $tmp_year);
            $a_ends = $T+($_POST[duration]*24*60*60);
                $a_ends = date("YmdHis", $a_ends);
                
                if($AUCTION['category'] != $_POST["category"]) {
                    // and increase http category counters
                    $ct = intval($_POST["category"]);
                    $row = mysql_fetch_array(mysql_query("SELECT * FROM PHPAUCTIONXL_categories WHERE cat_id=$ct"));
                    $counter = $row['counter']+1;
                    $subcoun = $row['sub_counter']+1;
                    $parent_id = $row['parent_id'];
                    mysql_query("UPDATE PHPAUCTIONXL_categories SET counter=$counter, sub_counter=$subcoun WHERE cat_id=$ct");
                    
                    // update recursive categories
                    while ( $parent_id!=0 )    {
                        // update this parent's subcounter
                        $rw = mysql_fetch_array(mysql_query("SELECT * FROM PHPAUCTIONXL_categories WHERE cat_id=$parent_id"));
                        $subcoun = $rw['sub_counter']+1;
                        mysql_query("UPDATE PHPAUCTIONXL_categories SET sub_counter=$subcoun WHERE cat_id=$parent_id");
                        // get next parent
                        $parent_id = intval($rw['parent_id']);
                    }
                    // and decrease auction category counters
                    $cta = intval($AUCTION['category']);
                    $row = mysql_fetch_array(mysql_query("SELECT * FROM PHPAUCTIONXL_categories WHERE cat_id=$cta"));
                    $counter = $row['counter']-1;
                    $subcoun = $row['sub_counter']-1;
                    $parent_id = $row['parent_id'];
                    mysql_query("UPDATE PHPAUCTIONXL_categories SET counter=$counter, sub_counter=$subcoun WHERE cat_id=$cta");
                    
                    // update recursive categories
                    while ( $parent_id!=0 ) {
                        // update this parent's subcounter
                        $rw = mysql_fetch_array(mysql_query("SELECT * FROM PHPAUCTIONXL_categories WHERE cat_id=$parent_id"));
                        $subcoun = $rw['sub_counter']-1;
                        mysql_query("UPDATE PHPAUCTIONXL_categories SET sub_counter=$subcoun WHERE cat_id=$parent_id");
                        // get next parent
                        $parent_id = intval($rw['parent_id']);
                    }
                }
            }


            $time = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),$tmp_month, $tmp_day,$tmp_year);
            $date = date("YmdHis",$time);

		if (!PHP_4 )
		{
		  require_once './htmlpurifier/library/HTMLPurifier.auto.php';
		  $config = HTMLPurifier_Config::createDefault();
		  $config->set('Core', 'Encoding', 'ISO-8859-1');
		  $config->set('HTML', 'Doctype', 'HTML 4.01 Transitional');
		  $config->set('HTML', 'AllowedElements', 'div,a,em,blockquote,p,code,pre,table,font,tbody,td,tr,b,strong,u,ul,li,ol');
		  $purifier = new HTMLPurifier($config);
		}
		else
		{
		   require_once './class/phpauction_purify.php';
		   $purifier = new HTMLPurifier();
		   $purifier->allowed_tags(array("div","a","em","blockquote","p","code","pre","table","font","tbody","td","tr","b","strong","u","ul","li","ol" ));
		}

        $clean_html = $purifier->purify(stripslashes($_POST[description]));
        $_POST['description'] = $clean_html;

            
            $sql="UPDATE PHPAUCTIONXL_auctions SET title=\"".AddSlashes($_POST["title"])."\",
                 category=\"".AddSlashes($_POST["category"])."\",
                description=\"".addslashes($clean_html)."\"                            
                                WHERE id='".AddSlashes($_POST["id"])."'";
            $res=mysql_query ($sql);
            
            if (!$res) {
                print "Database error on update: " . mysql_error();
                exit;
            } else {
                $updated = 1;
            }
                $URL = $_SESSION["RETURN_LIST"]."?offset=".$_SESSION['RETURN_LIST_OFFSET'];
                unset($_SESSION["RETURN_LIST"]);
                header("Location: $URL");
                exit;
        }
    } else {
        // COUNTRIES
        
        $country_list="";
        while (list ($code, $descr) = each ($countries)) {
            $country_list .= "<option value=\"$descr\"";
            if ($descr == $country) {
                $country_list .= " selected";
            }
            $country_list .= ">$descr</option>\n";
        }
        // NICKS (usernames)
        
        $userid_list = ""; // empty string to begin HTML list
        $userid_query = "select id, nick from PHPAUCTIONXL_users";
        $res_q = mysql_query($userid_query);
        if(!$res_q) {
            print "Database access error: abnormal termination".mysql_error();
            exit;
        }
        while($row = mysql_fetch_array($res_q)) {
            $userid_list .= "<option value='".$row['id']."'";
            if ($row['id'] == $userid) {
                $userid_list .= " selected ";
            }
            $userid_list .= ">".$row['nick']."</option>\n";
        }
        
        
        // DURATIONS
        
        $dur_list = ""; // empty string to begin HTML list
        $dur_query = "select days, description from PHPAUCTIONXL_durations";
        $res_d = mysql_query($dur_query);
        if(!$res_d) {
            print "Database access error: abnormal termination".mysql_error();
            exit;
        }
        for ($i = 0; $i < mysql_num_rows($res_d); $i++) {
            $row = mysql_fetch_row($res_d);
            // 0 is days, 1 is description
            // Append to the list
            $dur_list .= "<option value=\"$row[0]\"";
            // If this Durations # of days coresponds to the duration of this
            // auction, select it
            if ($row[0] == $duration) {
                $dur_list .= " selected ";
            }
            $dur_list .= ">$row[1]</option>\n";
        }
        
        $ERR = "ERR_112";
    }
    
}

if(!$_POST["action"] || ($_POST["action"] && !$updated)) {
    
    /*
    *        Make a large SQL query getting values from the "auctions"
    *        table and corresponding values that are indexed in other tables
    *         and displaying them both (and allowing the admin to change
    *        only the proper indexed values.
    */
    $query = "SELECT a.id, a.user as nick , u.nick as nick_description,
                a.title, a.starts, a.description,
                a.category, c.cat_name, a.suspended, a.current_bid,
                a.quantity, a.reserve_price, a.buy_now, a.location, a.minimum_bid
                FROM PHPAUCTIONXL_auctions a, 
                PHPAUCTIONXL_users u, 
                PHPAUCTIONXL_categories c
                WHERE u.id = a.user 
                AND c.cat_id = a.category 
                AND a.id='".$_REQUEST["id"]."'";
    $result = mysql_query($query);
    if(!$result) {
        print "Database access error: abnormal termination".mysql_error();
        exit;
    }
    
    $id = mysql_result($result,0,"id");
    $title = stripslashes(mysql_result($result,0,"title"));
    $userid = stripslashes(mysql_result($result,0,"nick"));
    $tmp_date = mysql_result($result,0,"starts");
    //$duration = mysql_result($result,0,"duration");
    $category = mysql_result($result, 0, "category");
    $cat_description = stripslashes(mysql_result($result,0,"cat_name"));
    $description = stripslashes(mysql_result($result,0,"description"));
    $suspended = mysql_result($result,0,"suspended");
    $current_bid = mysql_result($result,0,"current_bid");
    $min_bid = mysql_result($result,0,"minimum_bid");
    $quantity = mysql_result($result,0,"quantity");
    $reserve_price = mysql_result($result,0,"reserve_price");
    $buy_now = mysql_result($result,0,"buy_now");
    //$country = mysql_result($result, 0, "location");
    
    /*
    *         For all list-like items we create drop-down
    *        lists and select the index listed in the auction table.
    *        for this auction.
    */
    // NICKS (usernames)
    
    $userid_list = ""; // empty string to begin HTML list
    $userid_query = "select id, nick from PHPAUCTIONXL_users";
    $res_q = mysql_query($userid_query);
    if(!$res_q) {
        print "Database access error: abnormal termination".mysql_error();
        exit;
    }
    while($row = mysql_fetch_array($res_q)) {
        $userid_list .= "<option value='".$row['id']."'";
        if ($row['id'] == $userid) {
            $userid_list .= " selected ";
        }
        $userid_list .= ">$row[1]</option>\n";
    }
    
  
    // CATEGORIES
    $categories = mysql_query("SELECT * FROM PHPAUCTIONXL_categories_plain");
if($categories){
  while($cat_array=mysql_fetch_array($categories)){
    $cat_arrayaid[]=$cat_array['cat_id'];
    $cat_arrayaname[$cat_array['cat_id']]=$cat_array['cat_name'];
  }
  $categ = mysql_query("SELECT * FROM PHPAUCTIONXL_cats_translated WHERE lang='".$language."'");
  while($cat_array=mysql_fetch_array($categ)){
    $cat_arrayaname2[$cat_array['cat_id']]=$cat_array['cat_name'];
  }
  $j = 0;
  foreach($cat_arrayaid as $k=>$v){
    $category2 = $cat_arrayaname[$v];
    $num = 0;
    $i = 0;
    while ($i < strlen($category2))
	{
	  if (substr($category2,$i,6) == "&nbsp;" ) {
	    $num++;
		$i+=5;
	  }
	  $i++;
	}
    $cat_nuevas[$v]= num_space($num).$cat_arrayaname2[$v];
  }
  $TPL_categories_list = "<select name =\"category\">\n";
  foreach($cat_nuevas as $k=> $v){
    $TPL_categories_list.="<option value=\"".$k."\" ".(($k==$category)?"selected":"").">".$v."</option\n>";
  }
  $TPL_categories_list.="</select>\n";
}
    
    $country_list="";
    while (list ($code, $descr) = each ($countries)) {
        $country_list .= "<option value=\"$descr\"";
        if ($descr == $country) {
            $country_list .= " selected";
        }
        $country_list .= ">$descr</option>\n";
    }
    
    $date = mysql_result($result,0,"starts");
    $tmp_day = substr($date,6,2);
    $tmp_month = substr($date,4,2);
    $tmp_year = substr($date,0,4);
    if($SETTINGS[datesformat] == "USA") {
      $date = "$tmp_month/$tmp_day/$tmp_year";
    } else {
      $date = "$tmp_day/$tmp_month/$tmp_year";
    }
}

?>
<HTML>
<HEAD>
<link rel='stylesheet' type='text/css' href='style.css' />
<script type="text/javascript" src="../js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
	mode : "textareas",
	theme : "advanced",
	language: "en",
	plugins : "table",
	theme_advanced_buttons1 : "backcolor, forecolor, bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink",
	theme_advanced_buttons2 : "fontselect, fontsizeselect",
	theme_advanced_buttons3 : "tablecontrols",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	force_br_newlines : "false",
	extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]"
});
</script>
<link href="css/main.css" rel="stylesheet" type="text/css">
</HEAD>
<body bgcolor="#FFFFFF" text="#000000" link="#0066FF" vlink="#666666" alink="#000066" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr> 
    <td><table width="100%" border="0" cellspacing="0" cellpadding="0" class="titulo">
        <tr> 
          <td class="icono"><img src="images/auction_icon2.gif" width="31" height="25" ></td>
          <td class="breadcrumbs"><p><span><?=$MSG_239?></span>&nbsp;&gt;&gt;&nbsp;<?=$MSG_512?></p></td>
        </tr>
      </table></td>
  </tr>
  <tr>
    <td align="center" valign="middle">&nbsp;</td>
  </tr>
    <tr> 
    <td align="center" valign="middle">
<TABLE WIDTH="95%" BORDER="0" CELLSPACING="0" CELLPADDING="0"  ALIGN="CENTER" class="base"  style="border:1px solid #ccc;">
  <TR>
    <TD ALIGN=CENTER class=title><? print $MSG_512; ?></TD>
  </TR>
  <TR>
    <TD><FORM NAME=details ACTION="<? print basename($_SERVER['PHP_SELF']); ?>" METHOD="POST">
    <TABLE WIDTH="100%" BORDER="0" CELLPADDING="0" cellspacing="0" BGCOLOR="#FFFFFF">
                <?
                if($ERR || $updated){
                    print "<TR><TD></TD><TD WIDTH=486>";
                    if($$ERR) print $$ERR;
                    if($updated) print "Auction data updated";
                    print "</TD>
                </TR>";
                }
                ?>
                
                <TR>
                  <TD WIDTH="125" VALIGN="top" class="lineV gris"><p class="blue"><? print "$MSG_312 *"; ?> </p></TD>
                  <TD WIDTH="486" class="gris"><INPUT TYPE=text NAME=title SIZE=40 MAXLENGTH=255 VALUE="<? print $title; ?>">
                  </TD>
                </TR>
              <INPUT TYPE=hidden NAME=date SIZE=20 MAXLENGTH=20 VALUE="<? echo $date; ?>">
                        <TR>
                  <TD WIDTH="125"  VALIGN="top" class="lineV gris"><p class="blue"><? print "$MSG_316 *"; ?></p> </TD>
                  <TD WIDTH="486" class="gris"><? print $TPL_categories_list; ?> </TD>
                </TR>
                <TR>
                  <TD WIDTH="125" VALIGN="top" class="lineV"><p class="blue"><? print "$MSG_317 *"; ?></p> </TD>
                  <TD WIDTH="486"><TEXTAREA NAME=description COLS=85 ROWS=20><? echo $description; ?></TEXTAREA>
                  </TD>
                </TR>
                <!------------------------- item variants ------------------>
                <?
                if ($TPL_auction_variant!="") {
                ?>
                <TR>
                  <TD WIDTH="125" VALIGN="top" class="lineV gris"><p class="blue"><?print $MSG_25_0071;?></p></TD>
                  <TD WIDTH="486" class="gris"><? print $TPL_auction_variant; ?> </TD>
                </TR>
                <?
                }
                ?>
         <INPUT TYPE=hidden NAME="current_bid" SIZE=15 MAXLENGTH=15 VALUE="<? echo $current_bid; ?>">
                 
          <INPUT TYPE=hidden NAME="quantity" SIZE=40 MAXLENGTH=40 VALUE="1">
            
   <INPUT TYPE=hidden NAME="reserve_price" SIZE=40 MAXLENGTH=40 VALUE="<? echo
                $reserve_price; ?>">
                                <TR>
                  <TD WIDTH="125" VALIGN="top" class="lineV"><p class="blue"><? print "$MSG_300"; ?></p> </TD>
                  <TD WIDTH="486">
                  <?
                  if($suspended == 0)
                  print "$MSG_029";
                  else
                  print "$MSG_030";
                  ?>
                  </TD>
                </TR>
                <TR>
                  <TD WIDTH="204">&nbsp;</TD>
                  <TD WIDTH="486"><BR>
                    <BR>
                    <INPUT TYPE="submit" NAME="act" VALUE="<? print $MSG_089; ?>" class="action">
                  </TD>
                </TR>
              <tr>
              <td colspan="2">
              <INPUT TYPE="hidden" NAME="id" VALUE="<?=$_GET[id];?>">
              <INPUT TYPE="hidden" NAME="offset" VALUE="<?=$_GET[offset]; ?>">
              <INPUT TYPE="hidden" NAME="action" VALUE="update" /> <INPUT TYPE="hidden" NAME="security" VALUE="<?php echo $_SESSION['security'];?>" />
              </td>
              </tr>
            </TABLE> </FORM>
          </TD>
        </TR>
      </TABLE>
      </TD>
  </TR>
</TABLE>
</BODY>
</HTML>
